/**
 * Created by Administrator on 2017/6/24 0024.
 */
$(function () {
    $.showLoading('正在定位');
    /* + --------  定义地图参数对象  -------- + */
    var obj = {};
    obj.last_point = {};

    /* + --------  获取当前坐标  -------- + */
    var map, geolocation;
    //加载地图，调用浏览器定位服务
    SCOPE.map = map = new AMap.Map('map', {
        resizeEnable: true
    });

    console.log(sessionStorage.param_lat);
    console.log(sessionStorage.param_lng);
    if (sessionStorage.param_lat && sessionStorage.param_lng) {
        console.log(1);
        $(".amap-controls").html('<div class="amap-geolocation-con" style="position: absolute; z-index: 9999; right: 10px; bottom: 30%;"><div class="amap-geo"></div></div>');
        $(document).on('click', '.amap-geo', function () {
            map.setZoomAndCenter(14, [sessionStorage.position_lng, sessionStorage.position_lat]);
        });

        // todo 如果有保存位置信息  不重新获取定位
        obj.center_present_lng = obj.present_lng = sessionStorage.param_lng;
        obj.center_present_lat = obj.present_lat = sessionStorage.param_lat;
        setMapZoomAndCenter();
        sessionStorage.removeItem('param_lat');
        sessionStorage.removeItem('param_lng');
    } else if (sessionStorage.position_lat && sessionStorage.position_lng) {
        console.log(2);
        $(".amap-controls").html('<div class="amap-geolocation-con" style="position: absolute; z-index: 9999; right: 10px; bottom: 30%;"><div class="amap-geo"></div></div>');
        $(document).on('click', '.amap-geo', function () {
            map.setZoomAndCenter(14, [sessionStorage.position_lng, sessionStorage.position_lat]);
        });
        console.log(123);

        // todo 如果有保存位置信息  不重新获取定位
        obj.center_present_lng = obj.present_lng = sessionStorage.position_lng;
        obj.center_present_lat = obj.present_lat = sessionStorage.position_lat;
        setMapZoomAndCenter();
    } else {
        // todo 否则 重新定位
        map.plugin('AMap.Geolocation', function() {
            $.showLoading('正在定位');
            geolocation = new AMap.Geolocation({
                enableHighAccuracy: true,//是否使用高精度定位，默认:true
                timeout: 10000,          //超过10秒后停止定位，默认：无穷大
                maximumAge: 7 * 24 * 60 * 60 * 1000,  // 缓存定位结果
                buttonOffset: new AMap.Pixel(10, 20),//定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
                zoomToAccuracy: false,      //定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
                showCircle: false,        //定位成功后用圆圈表示定位精度范围，默认：true
                buttonPosition:'RB'
            });
            map.addControl(geolocation);
            geolocation.getCurrentPosition();
            AMap.event.addListener(geolocation, 'complete', onComplete);//返回定位信息
            AMap.event.addListener(geolocation, 'error', onError);      //返回定位出错信息
        });
    }



    //解析定位结果
    function onComplete(data) {
        console.log('定位成功000');
        $.loading_hide();
        var str=['定位成功'];

        // 使用本地存储记录用户位置信息
        sessionStorage.position_lat = data.position.getLat();
        sessionStorage.position_lng = data.position.getLng();

        obj.center_present_lng = obj.present_lng = data.position.getLng();
        obj.center_present_lat = obj.present_lat = data.position.getLat();
        setMapZoomAndCenter();
    }


    function setMapZoomAndCenter() {
        // 设置缩放级别和中心点
        map.setZoomAndCenter(14, [obj.present_lng, obj.present_lat]);
        set_amap_css();

        // 获取附近的活动
        if($(".get_nearby_activity").length > 0) {
            get_nearby_activity(obj, map);
        }

        $.hideLoading();
    }

    // 拖动
    //加载PositionPicker，loadUI的路径参数为模块名中 'ui/' 之后的部分
    AMapUI.loadUI(['misc/PositionPicker'], function(PositionPicker) {
        var positionPicker = new PositionPicker({
            mode:'dragMap',//设定为拖拽地图模式，可选'dragMap'、'dragMarker'，默认为'dragMap'
            map:map,//依赖地图对象
            iconStyle: { //自定义外观
                url: 'http://jx.mgtvshop.com/static/home/images/map_icon.png',
                ancher: [5, 32],
                size: [10, 25]
            }
        });
        positionPicker.start();

        //TODO:事件绑定、结果处理等
        positionPicker.on('success', function(positionResult) {
            // 定位成功 处理逻辑
            if ($(".show_friend_map").length > 0) {
                $("input[name='address']").val(positionResult.address);
                $(".activity_address").text(positionResult.address);
                // 保存位置中心点
                obj.center_present_lng = positionResult.position.lng;
                obj.center_present_lat = positionResult.position.lng;

            }
            if ($("input[name='lat']").length > 0) {
                $("input[name='lat']").val(positionResult.position.lat);
            }
            if ($("input[name='lng']").length > 0) {
                $("input[name='lng']").val(positionResult.position.lng);
            }

            if ($(".map_address").length > 0) {
                $('.map_address').text(positionResult.address);
            }

            $.hideLoading();

            // 首页拖动处理
            if ($(".index").length > 0) {
                if (!obj.last_point.lat) { // 当第一次的时候记录本次获取数据时候的中心点坐标
                    obj.last_point.lat = positionResult.position.lat;
                    obj.last_point.lng = positionResult.position.lng;
                    get_shop_list_by_category($('.js-menu').find('.msui_tabMenu-active'), map);
                } else {
                    var lnglat = new AMap.LngLat(obj.last_point.lng, obj.last_point.lat);
                    if(lnglat.distance([positionResult.position.lng, positionResult.position.lat]) > 10000) {
                        // 当拖动距离大于8000米的时候，重新获取数据 并跟新本次获取数据的坐标
                        obj.last_point.lat = positionResult.position.lat;
                        obj.last_point.lng = positionResult.position.lng;
                        get_shop_list_by_category($('.js-menu').find('.msui_tabMenu-active'), map);
                    }
                }
            }
        });
        positionPicker.on('fail', function(positionResult) {
            console.log('fail');
            console.log(positionResult)
        });
    });

    //解析定位错误信息
    function onError(data) {
        $.toptip('定位失败', 'error');
        $.hideLoading();
        $.loading_hide();
        $.confirm('定位失败，是否重新定位', function () {
            window.location.reload();
        });
    }

    // 修改地图的默认样式
    function set_amap_css() {
        $(".amap-copyright").remove();
        $(".amap-logo").remove();
        $(".amap-geolocation-con").css('bottom', '30%');
    }

    /* + --------  展示地图  -------- + */
    $(".show_friend_map").click(function () {
        $(".center").hide();
        $("#show_map").popup();
    });

    /* + --------  导航  -------- + */
    $(document).on('click', ".navigation", function () {
        var _this = $(this);
        obj.lat = _this.data('lat');
        obj.lng = _this.data('lng');
        var button = document.getElementById('bt');
        var cancel_bt = document.getElementById('cancel_bt');
        var map = new AMap.Map("map");
        navigation_init(button, map);
        $(".center").show();
    });

    var navigation_init = function (button, map) {
        console.log(obj);

        AMap.plugin(["AMap.Driving"], function() {
            var drivingOption = {
                policy:AMap.DrivingPolicy.LEAST_TIME,
                map:map
            };
            var driving = new AMap.Driving(drivingOption); //构造驾车导航类
            //根据起终点坐标规划驾车路线
            driving.search([obj.center_present_lng, obj.center_present_lat], [obj.lng, obj.lat], function(status,result){
                button.onclick = function(){
                    driving.searchOnAMAP({
                        origin:result.origin,
                        destination:result.destination
                    });
                };
                cancel_bt.onclick = function(){
                    console.log(obj);
                    map = new AMap.Map('map', {
                        resizeEnable: true,
                        zoom:14,
                        center: [obj.present_lng, obj.present_lat]
                    });
                    $(".center").hide();
                    get_nearby_activity(obj, map);
                }
            });
        });
        map.addControl(new AMap.ToolBar());
    };
});

